//封面图片
var coverImgArray = new Array();


/**
 * 上传
 * @param uploadId
 */
function upload(uploadId){
	$.plugin.plugLoading("正在上传图片，请稍后...");
	var uploadFile = $('#' + uploadId).val();
	var requestMapping = "";
	var flag = false;
	//只能上传一张图片
	if(coverImgArray.length > 0 && coverImgArray.length == 1){
		$.plugin.close();
		$.messager.alert("提示","只能上传一张图片！","info");
		return;
	}
	if(uploadFile == null || uploadFile.length < 1){
		$.plugin.close();
		$.messager.alert("提示","上传文件不能为空！","info");
		flag = false;
	}else{
		flag = true;
	}
	if(flag){
		$.ajaxFileUpload({
			 url: BASE_PATH + '/admin/wsProductController/uploadImage?type=' + uploadId,
		     secureuri:false,
		     fileElementId:''+uploadId+'', 
		     dataType: 'text', 
		     success: function (data){
		    	 var data = $(data).text();
		    	 var data = eval('('+data+')');
		    	 if(data && data.data && data.data.length > 0){
		    		 data = data.data;
		    		 for(var i = 0; i < data.length; i++){
		    			 $.plugin.close();
		    			 if(typeof(data[i].flag) != 'undefined' && data[i].flag){
				    		 var image = {"imageUrl":data[i].url,"imageType":data[i].type,"imgId":data[i].imgId,"imgName":data[i].imgName};
							 if(uploadId == 'cover'){ //封面图片
								image.imgIndex = coverImgArray.length;
								coverImgArray.push(image);
								appendImageToPage(uploadId, image);
								$('#coverSuccess').text(data[i].msg);
							 }
						 }else{
							 if(uploadId == 'cover'){
								$('#coverError').text('图片' + data[i].imgName + data[i].msg);
							 }
						 }
		    		 }
		    	 }
		     },
		     error: function (data, status, e){ 
		    	data = eval('('+data.responseText+')');
		    	if(data && data.data && data.data.length > 0){
		    		$.plugin.close();
		    		 data = data.data;
		    		 for(var i = 0; i < data.length; i++){
		    			 if(typeof(data[i].flag) != 'undefined' && data[i].flag){
		 					var image = {"imageUrl":data[i].url,"imageType":data[i].type,"imgId":data[i].imgId,"imgName":data[i].imgName};
		 					if(uploadId == 'cover'){
		 						image.imgIndex = coverImgArray.length;
		 						coverImgArray.push(image);
		 						appendImageToPage(uploadId, image);
		 						$('#coverSuccess').text(data[i].msg);
		 					}
		 				}else{
		 					 if(uploadId == 'cover'){
								$('#coverError').text('图片' + data[i].imgName + data[i].msg);
							 }
		 				}
		 		    }
		    	}
		    }
		});
	}
}

/**
 * 回显图片
 */
function appendImageToPage(uploadId, image){
	var url = BASE_PATH + '/' + image.imageUrl;
	var imageDiv = $('<div class="file-preview-frame" id="' + image.imgId + '" data-fileindex="' + image.imgIndex + '"></div>');
	var img = $('<img src="' + url + '" class="file-preview-image" title="' + image.imgName + '" alt="' + image.imgName + '" style="width:100px;height:132px;">');
	var divFooter = $('<div class="file-thumbnail-footer"></div>');
	var footerNameDiv = $('<div class="file-caption-name" title="' + image.imgName + '" style="width: 120px;">' + image.imgName + '</div>');
	var footerActionsDiv = $('<div class="file-actions"></div>');
	var footerButtonDiv = $('<div class="file-footer-buttons"></div>');
	var removeButton = $('<button type="button"  onclick="removeImage(\'' + image.imgId + '\',\''+image.imageUrl+'\')" class="kv-file-remove btn btn-xs btn-default" title="删除图片">删除</button>');
	var downloadButton = $('<a class="kv-file-remove btn btn-xs btn-default"   href="javascript:void(0)"  title="下载图片" onclick="downloadImages(\''+uploadId+'\')"> 下载</a>');
	var showButton = $('<a class="kv-file-remove btn btn-xs btn-default"    href="javascript:void(0)" title="预览图片" onclick="showImage(\''+url+'\',\''+image.imgId+'\')"> 预览</a>');
	var fixDiv = $('<div class="clearfix"></div>');
	removeButton.appendTo(footerButtonDiv);
	downloadButton.appendTo(footerButtonDiv);
	showButton.appendTo(footerButtonDiv);
	footerButtonDiv.appendTo(footerActionsDiv);
	fixDiv.appendTo(footerActionsDiv);
	footerNameDiv.appendTo(divFooter);
	footerActionsDiv.appendTo(divFooter);
	img.appendTo(imageDiv);
	divFooter.appendTo(imageDiv);
	$('#' + uploadId + 'ImagesDiv').append(imageDiv);
	$('#' + uploadId + 'FilePreview').show();
	$('#download' + uploadId).show();
}

/**
 * 预览图片
 * @param imageUrl
 * @param imgId
 */
function showImage(imageUrl,imgId){
	MainTab.createTab(imgId, '图片预览', BASE_PATH + '/admin/wsProductController/showProductImage?imageUrl='+imageUrl); //打开一个新页面
}

/**
 * 删除图片
 * @param imgId
 */
function removeImage(imgId,imageUrl,imageSmallUrl){
	var parent = $('#' + imgId).parent();
	var parentType = parent.attr('id').substring(0, parent.attr('id').indexOf('I'));
	var imageList = new Array();
	if(parentType == 'cover'){
		imageList = coverImgArray;
	}
	$('#' + imgId).remove();
	if($.trim(parent.html()) == ""){
		parent.parent().parent().hide();
	}
	if(imageList.length > 0){
		for(var i = 0; i < imageList.length; i++){
			if(imageList[i].imgId == imgId){
				imageList.splice(i,1);
				break;
			}
		}
		for(var j = 0; j < imageList.length; j++){
			imageList[j].imgIndex = j;
			$('#'+imageList[j].imgId).attr('data-fileindex', j);
		}
		//将数组制空
		coverImgArray.length = 0;
	}
	 
	if(coverImgArray.length == 0){
		$('#downloadcover').hide();
	}
}

/**
 * 下载图片
 * @param uploadId
 */
function downloadImages(uploadId){
	if(uploadId == 'cover'){
		imageUrl = getImagesUrl(coverImgArray);
	}
	
	window.location.href = BASE_PATH + '/admin/wsProductController/downloadImages?imageUrl=' + imageUrl;
}

/**
 * 获得图片地址
 * @param imageList
 * @returns
 */
function getImagesUrl(imageList){
	var imageUrl = '';
	for(var i = 0; i < imageList.length; i++){
		if(imageList[i].imageUrl != ''){
			imageUrl += imageList[i].imageUrl + ',';
		}
	}
	return imageUrl.substring(0, imageUrl.length - 1);
}

/**
 * 保存
 */
function saveProduct(flage){
	$.plugin.plugLoading("正在保存，请稍后...");
	var productName = $('#name').val();
	var productId = $('#productId').val();
	if(productName == null || productName == ''){
		$.plugin.close();
		$.messager.alert("提示","书名不允许为空!","info");
		return;
	}
	var linkUrl = $("#linkUrl").val();
	if(linkUrl != null && linkUrl != ''){
		if(checkURL(linkUrl) == false){
			$.plugin.close();
			$.messager.alert('错误','链接地址格式不正确!','error');
			return;
		}
	}
	var url = BASE_PATH + "/admin/wsProductController/checkProductName";
	$.ajax({
		type: 'POST',
		url: url, 
		data: {"productName":productName,"productId":productId}, 
		dataType: 'json',
		success: function(data) {
			if(data.success){//不重复
				$.plugin.close();
				submitForm(flage);
			}else{//重复
				$.plugin.close();
				$.messager.alert("提示","书名不允许重复!","info");
			}
		}
	});
}

/**
 * form提交
 */
function submitForm(flage){
	var formData = operateFormData();
	var url = "";
	if('add' == flage){
		url = BASE_PATH + "/admin/wsProductController/save"
	}else if('update' == flage){
		url = BASE_PATH + "/admin/wsProductController/update"
	}
	$.plugin.plugLoading("正在保存，请稍后...");
	$.ajax({
		type: 'POST',
		url: url, 
		data: formData, 
		dataType: 'json',
		success: function(data) {
			if(data && data != "null"){
				if(data.success){
					$.plugin.close();
					window.location.href = BASE_PATH + '/admin/wsProductController/toView/' + data.productId;
				}else{
					$.messager.alert("提示", data.msg, "info");
		    		$.plugin.close();
				}
			}
		}
	});
}

/**
 * 处理form中的数据
 */
function operateFormData(){
	if(coverImgArray != null && coverImgArray.length > 0){
		$('#coverImgList').val(JSON.stringify(coverImgArray));
	}
	var formData = form2object($('#form'));
	return formData;
}
/**
 * form表单中的端转变为object
 * @param $form
 * @returns {___anonymous879_880}
 */
function form2object($form){
   var obj = {};
   
   var formItemStr = $form.serialize();
   formItemStr = decodeURIComponent(formItemStr,true);
   var arr = formItemStr.split('&');
   for(var i=0;i<arr.length;i++){
      obj[arr[i].split('=')[0]] = arr[i].split('=')[1];
   }
   
   return obj;
}

/**
 * 校验链接地址
 */
function checkLinkUrl(){
	var linkUrl = $("#linkUrl").val();
	if(linkUrl != null && linkUrl != ''){
		if(checkURL(linkUrl) == false){
			$.messager.alert('错误','链接地址格式不正确!','error');
		}
	}
}

/**
 * 正则校验URL
 * @param string
 * @returns
 */
function checkURL(string){
	var strRegex = "^((https|http|ftp|rtsp|mms)?://)"         
        + "?(([0-9a-zA-Z_!~*'().&=+$%-]+: )?[0-9a-zA-Z_!~*'().&=+$%-]+@)?" //ftp的user@        
        + "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184        
        + "|" // 允许IP和DOMAIN（域名）        
        + "([0-9a-zA-Z_!~*'()-]+\.)*" // 域名- www.        
        + "([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\." // 二级域名        
        + "[a-zA-Z]{2,6})" // first level domain- .com or .museum        
        + "(:[0-9]{1,4})?" // 端口- :80        
        + "((/?)|"         
        + "(/[0-9a-zA-Z_!~*'().;?:@&=+$,%#-]+)+/?)$";        
	var re=new RegExp(strRegex); 
	return re.test(string);
}